# 保存为 convert_unicode.py
import os
import re
import codecs

def unicode_to_chinese(match):
    """将 \uXXXX 形式的 Unicode 转换为对应的字符"""
    code = match.group(1)
    return chr(int(code, 16))

def process_file(file_path):
    """处理单个文件，将其中的 \uXXXX 转换为对应的中文字符"""
    try:
        # 尝试读取文件内容
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()

        # 检查是否含有 \uXXXX 形式的 Unicode
        if re.search(r'\\u([0-9a-fA-F]{4})', content):
            print(f"  发现 Unicode 编码，正在转换...")

            # 替换 \uXXXX 为对应的字符
            new_content = re.sub(r'\\u([0-9a-fA-F]{4})', unicode_to_chinese, content)

            # 保存转换后的内容
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(new_content)

            print(f"  转换完成！")
        else:
            print(f"  没有发现需要转换的 Unicode 编码")

    except Exception as e:
        print(f"  处理文件时出错: {e}")

def traverse_directory(directory_path):
    """遍历指定目录及其子目录下的所有文件"""
    print(f"开始处理目录: {directory_path}")

    for root, dirs, files in os.walk(directory_path):
        for file in files:
            file_path = os.path.join(root, file)
            print(f"处理文件: {file_path}")
            process_file(file_path)

if __name__ == "__main__":
    # 设置要处理的目录路径
    directory_path = "src/main/java"  # 替换为你需要处理的目录路径
    traverse_directory(directory_path)
    print("所有文件处理完成！")